//
//  sinaWiboViewController.m
//  哎游
//
//  Created by 林程杰 on 15/1/11.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "macro.h"
#import "sinaWiboViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "UIImageView+WebCache.h"
#import "MyTravelsViewController.h"
#import "MyMusicViewController.h"
#import "Masonry.h"
#import "WebColor.h"
#import "Singleton.h"
#import "LoginViewCnntroller.h"
#import "AboutUsViewController.h"
#import "EmailSendViewController.h"

@implementation sinaWiboViewController

- (void)dealloc
{
    [_tableArray release];
    [_tableView release];
    [_button release];
    [_userImageView release];
    [_userName release];
    [super dealloc];
}

- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];


    }
    return self;
}

- (void) viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.cameraBool = YES;//判断刷新后是否还要走ViewWill的本地登陆, 初始值是yes
    NSString *str = @"我的收藏";
    NSString *str1 = @"我的音乐";
    NSString *str2 = @"清除缓存";
    NSString *str3 = @"版本更新";
    NSString *str4 = @"关于我们";
    NSString *str5 = @"意见反馈";
    [self.tableArray addObject:str];
    [self.tableArray addObject:str1];
    [self.tableArray addObject:str2];
    [self.tableArray addObject:str3];
    [self.tableArray addObject:str4];
    [self.tableArray addObject:str5];
    
    self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [self judgeButton];
    
    if (IOS_VERSION >= 7.0) {
        self.navigationController.navigationBar.barTintColor = [WebColor seaGreen];
    }
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [button setBackgroundImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 100)];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.backgroundColor = [UIColor clearColor];
    label.text = @"我的主页";
    self.navigationItem.titleView = label;
    [button release];
    [label release];

    [self creatView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self judgeButton];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"login"];
    NSString *state = [user objectForKey:@"state"];
    if ([str isEqualToString:@"yes"]) {
        if ([state isEqualToString:@"sina"]) {
            
            [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
                NSLog(@"%d",result);
                NSString *uid = [userInfo uid];
                NSString *nickname = [userInfo nickname];
                [_imageView removeFromSuperview];
                [_imageViewState sd_setImageWithURL:[NSURL URLWithString:[userInfo profileImage]] placeholderImage:nil];
                
                
                [_stateBtn setTitle:[userInfo nickname] forState:UIControlStateNormal];
                [_stateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                _stateBtn.titleLabel.textAlignment = UITextAlignmentCenter;
            }];
        }else{
            //本地登录
            if (_cameraBool == YES) {
                
                _imageViewState.image = [UIImage imageNamed:@"loginState.png"];
                [_imageViewState setBackgroundColor:[UIColor whiteColor]];
                _backGroungImageView.userInteractionEnabled = YES;
                
                [_stateBtn setTitle:@"点击设置头像" forState:UIControlStateNormal];
                [_stateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_stateBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
                
                _stateBtn.titleLabel.textAlignment = UITextAlignmentCenter;
                
                [_stateBtn addTarget:self action:@selector(cameraUse:) forControlEvents:UIControlEventTouchUpInside];
            }
            
        }
    }

    [self judge];
}

- (void)judgeButton
{
    [self.button removeTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_button];
    if ([[user objectForKey:@"login"] isEqualToString:@"yes"]) {
        [_button setTitle:@"注销" forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(logoutSinaWeibo:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        [_button setTitle:@"登录" forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(userLogin:) forControlEvents:UIControlEventTouchUpInside];
    }
    [_button release];
}

- (void) creatView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell1"];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    self.backGroungImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    _backGroungImageView.backgroundColor = [WebColor seaGreen];
    [self.view addSubview:_backGroungImageView];
    [_backGroungImageView release];
    
    
    
    //建一个公共的视图
    self.imageViewState = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 35, _backGroungImageView.frame.size.height / 2 - 35, 70, 70)];
    _imageViewState.layer.cornerRadius = 35;
    _imageViewState.clipsToBounds = YES;
    [_backGroungImageView addSubview:_imageViewState];
    
    self.stateBtn = [[UIButton alloc] init];
    _stateBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_backGroungImageView addSubview:_stateBtn];
    
    [_stateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imageViewState.mas_bottom).offset(20);
        make.left.equalTo(_backGroungImageView.mas_left).offset(0);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 30));
    }];
        
    
}

- (void) judge
{
    //判断登陆方式
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"login"];
    NSString *state = [user objectForKey:@"state"];
    
     [self createTableHeaderView];

}


- (void)createTableHeaderView
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *state = [user objectForKey:@"state"];
    if ([[user objectForKey:@"login"] isEqualToString:@"yes"]) {
        if ([state isEqualToString:@"sina"]){
            //加载风火轮
            self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, self.view.frame.size.height / 8, 60, 60)];
            _imageView.image = [UIImage imageNamed:@"fireLogin.png"];
            _imageView.layer.cornerRadius = 30;
            _imageView.clipsToBounds = YES;
            [self.view addSubview:_imageView];
            
            CABasicAnimation* rotationAnimation;
            rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
            rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
            [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            rotationAnimation.duration = 2;
            rotationAnimation.RepeatCount = 10000;
            rotationAnimation.cumulative = NO;
            rotationAnimation.removedOnCompletion = NO;
            rotationAnimation.fillMode = kCAFillModeBoth;
            [_imageView.layer addAnimation:rotationAnimation forKey:@"rotation"];
            [_imageView release];
        }else{
            _imageView = nil;
        }
            
        }

    [self.tableView.tableHeaderView addSubview:_imageView];
    self.tableView.tableHeaderView = _backGroungImageView;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    
    cell.textLabel.text = [_tableArray objectAtIndex:indexPath.row];
    return cell;
}

- (void) logoutSinaWeibo : (id) sender
{
    Singleton *share = [Singleton shareInstance];
    if (share.loginState == SinaLogin) {
        [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
    }
    [self.navigationController popViewControllerAnimated:NO];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定退出?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.delegate = self;
       [alert show];
    [alert release];
    _cameraBool = YES;
    
}

- (void)userLogin:(id)sender
{
    LoginViewCnntroller *login = [[LoginViewCnntroller alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
    [login release];
    [nav release];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"login"];
    BOOL equal = [str isEqualToString:@"yes"];
    if (indexPath.row == 0) {
        if (equal == YES) {
            MyTravelsViewController *my = [[MyTravelsViewController alloc] init];
            [self.navigationController pushViewController:my animated:YES];
            [my release];
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
    }else if (indexPath.row == 1) {
        if (equal == YES) {
            MyMusicViewController *my =[[MyMusicViewController alloc] init];
            [self.navigationController pushViewController:my animated:YES];
            [my release];
        } else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
    } else if (indexPath.row == 2) {
        [[SDImageCache sharedImageCache] clearDisk];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    } else if (indexPath.row == 3) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请期待2.0" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }else if(indexPath.row == 4){
        AboutUsViewController *about = [[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:about animated:YES];
        [about release];
    }else{
        EmailSendViewController *email = [[EmailSendViewController alloc] init];
        [self.navigationController pushViewController:email animated:YES];
        [email release];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    Singleton *share = [Singleton shareInstance];
    if (buttonIndex == 1) {
        share.loginState = Tourist;
        [user setObject:@"no" forKey:@"login"];
        [user setValue:@"tourist" forKey:@"state"];
        _userName.text = nil;
        _userImageView.image = nil;
        
        _imageViewState.image = nil;
        [_imageViewState setBackgroundColor:[WebColor seaGreen]];
        _stateBtn.titleLabel.text = nil;
        
        [self judgeButton];
      
    }
}

- (void) returnBack
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//用相机调用头像
- (void)cameraUse : (id) sender
{
    //这里先判断是否有相机，如果没有弹窗警告
    self.imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.allowsEditing = YES;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        _imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    }
    [self presentViewController:_imagePicker animated:YES completion:nil];
    [_imagePicker release];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //选取图片调用
    if ([mediaType isEqualToString:@"public.image"]) {
        //        [_headPic setBackgroundImage:[info objectForKey:UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
        
            _imageViewState.image = [info objectForKey:UIImagePickerControllerOriginalImage];
       
        _cameraBool = NO;
        
    }else
    {
        NSLog(@"Error media type");
        return;
    }
}






@end
